<template>
  <div>
    <yj-dialog
      :modal="dialog.modal"
      :width="dialog.width"
      :title="dialog.title"
      :dialogVisible="dialog.visible"
      @close="closeDialog"
    >
      <template slot="dialog-content">
        <el-form
          :model="form"
          :rules="rules"
          ref="userForm"
          size="mini"
          label-width="100px"
        >
          <el-form-item label="商品名称" :rule="rules" prop="goodName">
            <el-input
              v-model="form.goodName"
            ></el-input>
          </el-form-item>

          <el-form-item label="商品类型" prop="typeNo">
            <el-select style="width: 100%" filterable v-model="form.typeNo" placeholder="请选择商品类型">
              <el-option
                v-for="item in goodsTypes"
                :key="item.typeNo"
                :label="item.name"
                :value="item.typeNo">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="商品原价" prop="price">
            <el-input-number style="width: 100%" v-model="form.price" :mini="0" :precision="2" :step="0.1"
                             :max="1000"></el-input-number>
          </el-form-item>

          <el-form-item label="积分价" prop="integralPrice">
            <el-input-number style="width: 100%" v-model="form.integralPrice" :mini="0" :step="1"
                             :max="1000"></el-input-number>
          </el-form-item>

          <el-form-item label="库存" prop="stock">
            <el-input-number style="width: 100%" v-model="form.stock" :mini="0" :step="1" :max="1000"></el-input-number>
          </el-form-item>

          <el-form-item label="商品简单描述" prop="content">
            <el-input
              type="textarea"
              :rows="4"
              placeholder="请输入内容"
              v-model="form.content">
            </el-input>
          </el-form-item>

          <el-form-item label="上下架" prop="status">
            <el-switch inactive-color="#909399" active-color="#67C23A" :active-value="CONST.status.ON"
                       :inactive-value="CONST.status.OFF" inactive-text="下架" active-text="上架"
                       v-model="form.status"></el-switch>
          </el-form-item>


          <el-form-item label="商品图片" prop="status">

            <el-upload
              :auto-upload="false"
              class="avatar-uploader"
              :on-change="onChangeFile"
              accept="image/png,image/jpg,image/jpeg"
              :show-file-list="false">
              <img v-if="form.mainImgUrl" :src="form.mainImgUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            <div v-if="form.mainImgUrl" class="delele-img" @click="removeFile">删除</div>

          </el-form-item>


        </el-form>

        <div slot="footer" style="text-align: center" class="dialog-footer">
          <el-button size="mini" @click="cancelDialogBtn('userForm')"
          >取 消
          </el-button
          >
          <el-button
            size="mini"
            type="primary"
            @click="saveDialogBtn('userForm')"
          >确 定
          </el-button
          >
        </div>
      </template>
    </yj-dialog>

    <table-frame
      ref="frame"
      :getDataUrl="prop.getDataUrl"
      :removeUrl="prop.removeUrl"
      :searchShow="prop.searchShow"
      :operateShow="prop.operateShow"
      :location="prop.location"
      :searchModel="prop.searchModel"
      :reloadTable="prop.reloadTable"
      :colunmsCount="prop.colunmsCount"
      :showDelBtn="prop.showDelBtn"
      :delBtnPermission="prop.delBtnPermission"
    >
      <template slot="top_operate" slot-scope="currentRow">
        <auth :code="permission.add">
          <template slot="auth">
            <el-button
              type="primary"
              icon="el-icon-plus"
              @click="add()"
              size="mini"
            >添加
            </el-button
            >
          </template>
        </auth>

        <!-- <el-button type="success" icon="el-icon-edit" @click="add()" size="mini">修改</el-button> -->
      </template>

      <template slot="columns">
        <el-table-column align="center" show-overflow-tooltip prop="goodName" label="商品名称"></el-table-column>
        <el-table-column align="center" prop="stock" label="商品库存"></el-table-column>
        <el-table-column align="center" prop="typeName" label="类型"></el-table-column>
        <el-table-column align="center" prop="status" label="上/下架">
          <template slot-scope="scope">
            <el-switch
              disabled
              @change="v=>activitySwitch(v,scope.row.id)"
              style="display: block"
              v-model="scope.row.status"
              active-color="#13ce66"
              inactive-color="#ff4949"
              active-text=""
              active-value="上架"
              inactive-value="下架"
              inactive-text="">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="price" label="原价"></el-table-column>
        <el-table-column align="center" prop="integralPrice" label="积分价"></el-table-column>
        <el-table-column align="center" prop="mainImgUrl" label="商品图片">
          <template slot-scope="scope">
            <el-image fit="cover" style="width:50px;height: 50px" :preview-src-list="[scope.row.mainImgUrl]"
                      :src="scope.row.mainImgUrl"/>
          </template>
        </el-table-column>
        <el-table-column align="center" show-overflow-tooltip prop="content" label="商品描述"></el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="createTime"
          sortable
          width="150"
          align="center"
          label="创建时间"
        ></el-table-column>
        <el-table-column
          prop="updateTime"
          show-overflow-tooltip
          sortable
          align="center"
          width="150"
          label="更新时间"
        ></el-table-column>
      </template>
      <template slot="operate">
        <el-table-column fixed="right" align="center" label="操作" width="300">
          <template slot-scope="scope">
            <auth :code="permission.update">
              <template slot="auth">
                <el-button
                  class="operate-btn"
                  icon="el-icon-edit"
                  type="text"
                  @click="edit(scope.row)"
                  size="mini"
                  slot="auth"
                >修改
                </el-button
                >
              </template>
            </auth>
            <auth v-if="scope.row.status=='上架'" :code="permission.changeStatus">
              <template slot="auth">
                <el-button
                  class="operate-btn"
                  icon="el-icon-bottom"
                  type="text"
                  @click="changeStatus(scope.row)"
                  size="mini"
                  slot="auth"
                >下架
                </el-button
                >
              </template>
            </auth>
            <auth v-if="scope.row.status=='下架'" :code="permission.changeStatus">
              <template slot="auth">
                <el-button
                  class="operate-btn"
                  icon="el-icon-top"
                  type="text"
                  @click="changeStatus(scope.row)"
                  size="mini"
                  slot="auth"
                >上架
                </el-button
                >
              </template>
            </auth>
            <auth :code="permission.goodsStock">
              <template slot="auth">
                <el-button
                  class="el-icon-s-opportunity"
                  type="text"
                  @click="stockDbClick(scope.row)"
                  size="mini"
                  slot="auth"
                >增加库存
                </el-button
                >
              </template>
            </auth>
            <auth :code="permission.remove">
              <template slot="auth">
                <el-button
                  class="operate-btn"
                  icon="el-icon-delete"
                  type="text"
                  v-if="scope.row.username != 'admin'"
                  @click="del(scope.row.id)"
                  size="mini"
                  slot="auth"
                >删除
                </el-button
                >
              </template>
            </auth>
          </template>
        </el-table-column>
      </template>
    </table-frame>
  </div>
</template>
<script>
let _this = {};
import searchModel from "./Search.vue";
import utils from "../../../utils/CommonUtils.js";
import formUtils from "../../../utils/form.js";

export default {
  data() {
    return {
      dialog: {
        width: "40%",
        title: "新增/修改",
        visible: false,
        modal: true,
      },
      prop: {
        searchShow: true,
        operateShow: true,
        location: " 系统设置 / 岗位管理",
        getDataUrl: "/goods/pageList",
        removeUrl: "/goods/remove/?",
        searchModel: searchModel,
        reloadTable: false,
        showDelBtn: true,
        isPage: true,
        delBtnPermission: "goods:del"
      },
      CONST: {
        status: {ON: "ON", OFF: "OFF"}
      },
      form: {
        id: "",
        price: 0,
        integralPrice: 0,
        goodName: "",
        typeNo: "",
        mainImgUrl: "",
        stock: 0,
        status: "ON",
        content: '',
        remark: '',
      },
      formStrInit: '',

      permission: {
        add: "goods:add",
        remove: "goods:del",
        update: "goods:update",
        changeStatus: "goods:changeStatus",
        goodsStock: "goods:stock:add",
      },
      goodsTypes: [],
      rules: {
        id: [{required: false}],
        positionName: [
          {required: true, message: "请输入用户名", trigger: "blur"}
        ],
        positionCode: [
          {required: true, message: "请输入登陆名", trigger: "blur"},
        ],
        remark: [{required: false}],
      },
      URL: {
        save: "/goods/save",
        update: "/goods/update",
        remove: "/goods/remove/?",
        changeStatus: "/goods/changeStatus",
        addStock: "/goods/addStock"
      },
    };
  },
  created() {
    formUtils.initFormStr(this, 'formStrInit', this.form);
    this.initType();
  },
  methods: {
    activitySwitch(v, id) {

    },
    initType() {
      this.$get("/goods/goodsType", {}).then(res => {
        if (res.R) {
          this.goodsTypes = res.data;
        }
      })
    }
    // 添加
    , add() {
      this.dialog.visible = true;
      this.setDataToForm(null);
    },
    // 编辑
    edit(row) {
      row.status = row.status === '上架' ? this.CONST.status.ON : this.CONST.status.OFF
      this.setDataToForm(row);
      this.dialog.visible = true;
    },
    // 取消
    cancelDialogBtn(userForm) {
      this.dialog.visible = false;
      this.setDataToForm(null);
      this.$refs[userForm].resetFields();
    },
    closeDialog() {
      this.$emit("closeModal", false);
    },
    // 增加库存
    stockDbClick(row) {
      this.$prompt('请输入要增加的数量', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(({value}) => {
        if (!utils.isInteger(value)) {
          this.$error("请输入正确的数值")
          this.stockDbClick(row);
          return;
        }
        formUtils.put(this, this.URL.addStock, {id: row.id, stock: value}, true, res => {
          this.reqResult(res)
        })
      }).catch(() => {
      });
    },
    saveDialogBtn(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          if (this.form.id != null && this.form.id != '') {
            this.update();
            return;
          }
            this.save();
        } else {
          this.$warning("缺少必填数据");
          return false;
        }
      });
    },
    save() {
      formUtils.post(this, this.URL.save, this.form, true, res => {
        this.reqResult(res)
      })
    }
    , update() {
      formUtils.post(this, this.URL.update, this.form, true, res => {
        this.reqResult(res)
      })
    },

    // 上架/下架
    changeStatus(row) {
      formUtils.put(this, this.URL.changeStatus, {id: row.id, status: row.status === '上架' ? 'OFF' : 'ON'}, true, null)
    },
    del(id) {
      formUtils.delete(this, this.URL.remove.replace("?", id), true, "", null)
    },
    reqResult(res) {
      this.dialog.visible = false;
      this.setDataToForm(null);
    }
    , setDataToForm(row) {
      formUtils.setDataToForm(this, 'form', row, [], JSON.parse(this.formStrInit))
    },
    reloadTable() {
      _this = this;
      this.prop.reloadTable = true;
      setTimeout(() => {
        _this.prop.reloadTable = false;
      }, 1000);
    },
    onChangeFile(file, list) {
      if (file.size > this.$globConfig.fileMaxSize) {
        // 文件大于5m
        this.$warning("文件不能大于" + (this.$globConfig.fileMaxSize / 1024 / 1024) + "MB");
        return;
      }
      utils.fileToBase64(file).then(res => {
        this.form.mainImgUrl = res;
      })
    }
    , removeFile() {
      this.form.mainImgUrl = "";
    }
  },
};
</script>
<style>
</style>
<style scoped>
.operate-btn {
  margin: 0 5px;
}

.delele-img {
  font-size: 14px;
  width: 178px;
  cursor: pointer;
  text-align: center;
}

.avatar-uploader >>> .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
